package com.linshidream.intrachat.simplenio;

import com.linshidream.intrachat.simplenio.pipeline.*;
import com.linshidream.intrachat.simplenio.pipeline.boots.MiniEventLoopGroup;
import com.linshidream.intrachat.simplenio.pipeline.boots.MiniServerBootstrap;
import com.linshidream.intrachat.simplenio.pipeline.context.MiniChannel;
import com.linshidream.intrachat.simplenio.pipeline.handler.MiniChannelInitializer;
import com.linshidream.intrachat.simplenio.pipeline.hearbeat.HeartbeatHandler;
import com.linshidream.intrachat.simplenio.pipeline.hearbeat.MiniIdleStateHandler;

/**
 * Created on 2025/8/17 18:21
 *
 * @author linshidream
 * @version 1.0.0
 * @description
 */

public class MiniNettyServer {
    public static void main(String[] args) {
        MiniEventLoopGroup workGroup = new MiniEventLoopGroup(4);

        try {
            MiniServerBootstrap bootstrap = new MiniServerBootstrap();
            bootstrap.group(workGroup)
                    .childHandler(new MiniChannelInitializer() {
                        @Override
                        public void initChannel(MiniChannel ch) {
                            // 超过 6s 不读不写，就会触发空闲事件
                            ch.pipeline().addLast("MiniIdleStateHandler", new MiniIdleStateHandler(6000, 6000));
                            ch.pipeline().addLast("Encoder", new LengthFieldMessageEncoder());
                            ch.pipeline().addLast("Decoder", new LengthFieldMessageDecoder());

                            // 触发空闲事件后，发送ping,连续3次没收到 pong 断开连接
                            ch.pipeline().addLast("HeartbeatHandler", new HeartbeatHandler(3));
                            ch.pipeline().addLast("LoggerHandler", new LoggerHandler());
                            ch.pipeline().addLast("ServerCheckHandler", new ServerCheckHandler());
                            ch.pipeline().addLast("ServerEchoHandler", new ServerEchoHandler());
                        }
                    })
                    .bind(10030)
                    .sync();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            workGroup.shutdownGracefully();
        }
    }
}